import axios from 'axios'
import { message } from 'ant-design-vue'
import { API_BASE_URL } from '@/config/env'

// 创建 Axios 实例
const myAxios = axios.create({
  baseURL: API_BASE_URL,
  timeout: 60000,
  withCredentials: true,  //携带cokkie
})

// 全局请求拦截器
myAxios.interceptors.request.use(
  function (config) {
    // 调试信息：记录所有请求
    if (config.url?.includes('deploy') || config.url?.includes('app') || config.url?.includes('chatHistory')) {
      console.log('发送请求:', {
        url: config.url,
        method: config.method,
        data: config.data,
        params: config.params
      })
    }
    return config
  },
  function (error) {
    // Do something with request error
    return Promise.reject(error)
  },
)

// 全局响应拦截器
myAxios.interceptors.response.use(
  function (response) {
    // 调试信息：记录应用相关响应
    if (response.config.url?.includes('deploy') || response.config.url?.includes('app') || response.config.url?.includes('chatHistory')) {
      console.log('接收响应:', {
        url: response.config.url,
        status: response.status,
        data: response.data
      })
    }
    
    const { data } = response
    // 未登录
    if (data.code === 40100) {
      // 不是获取用户信息的请求，则提示登录
      if (!response.request.responseURL.includes('user/get/login')) {
        message.warning('请先登录')
        // 使用模态框登录，不再跳转页面
      }
    }
    return response
  },
  function (error) {
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    return Promise.reject(error)
  },
)

export default myAxios
